/*

  *   This file exports some utlies functions that will
  * be used through the site. 


*/


/*
  *
  * module dependences
  *
*/

var crypto = require("crypto");



//-----constans--------
var salt_length = 5;

var alphbat = [
    'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
    'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
    '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ':', ';', '<', '=', '>', '?', '@'];

//because javascript time functions deal with millseconds,so it is convinent to pre defined some values
var time = {
    second:1000,
    minute:60000,
    hour  :3600000,
    day   :86400000

};

//---------------------

exports.alphbat = alphbat;
exports.time = time;

//---------------------
//
//for test
exports.hello = function(){ 
    return "hello";
}

//random generate a salt of length salt_length
//The salt elements come from the alphbat defined above.
//
//useage: var salt = generate_salt();
//
exports.generate_salt = function(){


    var res = "";
    for(var i = 0;i < salt_length;++i){
	var index = Math.floor(Math.random() * alphbat.length);
	res += alphbat[index];
    }
//    console.log("result: " + res);
    return res;
}


//add and hash the salted password
//
//usage: var new_password = password_salt(password,salt);
//
exports.password_salt = function(password,salt){
    
    return hash_password(password,salt);
}


/*generate the millseconds of the time
 *argument:
 * {
 *   days:...,hours:...,minutes:...,seconds:...
 * }
 * carefually handles the null situations
 * but not handler the negative situations.
*/
exports.generate_time = function(time_stamp){

    var days = time_stamp.days || 0;
    var hours = time_stamp.hours || 0;
    var minutes = time_stamp.miutes || 0;
    var seconds = time_stamp.seconds || 0;
    
    return days * time.day + hours * time.hour + minutes * time.minute + seconds * time.second;
}


//---------------------------------------
//----private functions------------------
//---------------------------------------


function hash_password(password,salt){
    
    return hash_password_sha1(password,salt);

}

function hash_password_md5(password,salt){

    var md5 = crypto.createHmac("md5",salt);
    return md5.update(password).digest("base64");
}


function hash_password_sha1(password,salt){

    var sh = crypto.createHmac("sha1",salt);
    return sh.update(password).digest("base64");
}

//test functions

function test(){

    console.log(hash_password("agvasfsa","abc"));
};

//test();



